package com.kefu.web.im.util;

import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.UUID;

import org.jasypt.util.text.BasicTextEncryptor;

import com.kefu.web.im.config.IMDataContext;

public class CommonTools {

	private static MD5 md5 = new MD5();

	public static SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

	public static SimpleDateFormat timeRangeDateFormat = new SimpleDateFormat("HH:mm");

	public static String getUUID() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	/**
	 * 当前时间+已过随机生成的 长整形数字
	 * 
	 * @return
	 */
	public static String genID() {
		return Base62.encode(getUUID()).toLowerCase();
	}

	public static String genIDByKey(String key) {
		return Base62.encode(key).toLowerCase();
	}

	public static String getContextID(String session) {
		return session.replaceAll("-", "");
	}

	public static String md5(String str) {
		return md5.getMD5ofStr(md5.getMD5ofStr(str));
	}

	public static String md5(byte[] bytes) {
		return md5.getMD5ofByte(bytes);
	}

	/***
	 * ID编码 ， 发送对话的时候使用
	 * 
	 * @param id
	 * @param nid
	 * @return
	 */
	public static String genNewID(String id, String nid) {
		StringBuffer strb = new StringBuffer();
		if (id != null && nid != null) {
			int length = Math.max(id.length(), nid.length());
			for (int i = 0; i < length; i++) {
				if (nid.length() > i && id.length() > i) {
					int cur = (id.charAt(i) + nid.charAt(i)) / 2;
					strb.append((char) cur);
				} else if (nid.length() > i) {
					strb.append(nid.charAt(i));
				} else {
					strb.append(id.charAt(i));
				}
			}
		}
		return strb.toString();
	}
	
	/**
     * 
     * @param str
     * @return
     * @throws NoSuchAlgorithmException 
     */
    public static String encryption(String str) throws NoSuchAlgorithmException{
    	BasicTextEncryptor textEncryptor = new BasicTextEncryptor ();
    	textEncryptor.setPassword(IMDataContext.getSystemSecrityPassword());
    	return textEncryptor.encrypt(str);
    }
    
    /**
     * 
     * @param str
     * @return
     * @throws NoSuchAlgorithmException 
     */
    public static String decryption(String str) throws NoSuchAlgorithmException{
    	BasicTextEncryptor textEncryptor = new BasicTextEncryptor ();
    	textEncryptor.setPassword(IMDataContext.getSystemSecrityPassword());
    	return textEncryptor.decrypt(str);
    }
}
